<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>摄像头控制台</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f4f4f9;
        }
        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        #video_feed {
            margin-top: 20px;
            border: 1px solid #ccc;
            border-radius: 8px;
        }
        button {
            margin: 10px;
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: white;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .camera-list {
            margin: 10px 0;
            width: 100%;
        }
        .camera-item {
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin: 5px 0;
            cursor: pointer;
            background-color: #f9f9f9;
        }
        .camera-item:hover {
            background-color: #e9e9e9;
        }
        .status-indicator {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            margin-left: 10px;
            display: inline-block;
        }
        .status-on {
            background-color: green;
        }
        .status-off {
            background-color: red;
        }
        .camera-details {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f9f9f9;
            width: 100%;
            white-space: pre-wrap; /* 使文字换行 */
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>摄像头控制台</h1>
        <div class="camera-list" id="camera-list">
            <!-- 摄像头列表将由 JavaScript 动态加载 -->
        </div>
        <div>
            <button onclick="captureImage()">拍摄图片</button>
            <button onclick="startVideoFeed()">开始实时预览</button>
            <button onclick="stopVideoFeed()">停止实时预览</button>
            <button onclick="closeCamera()">关闭摄像头</button>
            <span id="camera-status" class="status-indicator status-off"></span>
        </div>
        <div>
            <img id="captured_image" src="" alt="拍摄的图片" style="display: none; max-width: 100%; border-radius: 8px;">
            <img id="video_feed" src="" alt="实时视频流" style="display: none; max-width: 100%; border-radius: 8px;">
        </div>
        <div class="camera-details" id="camera-details">
            <h2>摄像头详情</h2>
            <pre id="camera-info">请选择一个摄像头以查看详情。</pre>
        </div>
    </div>

    <script>
        // 动态加载可用的摄像头
        function loadCameras() {
            console.log("开始扫描摄像头...");
            fetch('/scan_cameras')
                .then(response => response.json())
                .then(cameras => {
                    console.log("扫描完成，找到以下摄像头：", cameras);
                    const cameraList = document.getElementById('camera-list');
                    cameraList.innerHTML = '';  // 清空现有内容
                    if (cameras.length === 0) {
                        console.log("未找到可用摄像头。");
                        cameraList.innerHTML = '<div>未找到可用摄像头。</div>';
                    } else {
                        cameras.forEach(camera => {
                            const item = document.createElement('div');
                            item.className = 'camera-item';
                            item.textContent = `摄像头 ${camera.index}: ${camera.name}`;
                            item.onclick = () => setCamera(camera.index);  // 确保传递 camera.index
                            cameraList.appendChild(item);
                        });
                        // 默认选择第一个摄像头
                        setCamera(cameras[0].index);
                    }
                })
                .catch(error => {
                    console.error("扫描摄像头时出错：", error);
                });
        }

        // 设置当前摄像头
        function setCamera(cameraIndex) {
            console.log(`正在切换到摄像头 ${cameraIndex}...`);
            fetch(`/set_camera/${cameraIndex}`, { method: 'POST' })
                .then(response => response.json())
                .then(data => {
                    console.log('当前摄像头设置为:', data.camera_index);
                    alert(`已切换到摄像头 ${data.camera_index}`);
                    updateCameraStatus(true);
                    fetchCameraDetails(cameraIndex);
                })
                .catch(error => {
                    console.error("切换摄像头时出错：", error);
                });
        }

        // 获取摄像头详情
        function fetchCameraDetails(cameraIndex) {
            console.log(`正在获取摄像头 ${cameraIndex} 的详情...`);
            fetch(`/camera_details/${cameraIndex}`)
                .then(response => response.json())
                .then(details => {
                    console.log('摄像头详情:', details);
                    const cameraInfo = document.getElementById('camera-info');
                    cameraInfo.textContent = details.info; // 直接显示 info 字段内容
                })
                .catch(error => {
                    console.error("获取摄像头详情时出错：", error);
                });
        }

        // 拍摄一张图片
        function captureImage() {
            console.log("正在拍摄图片...");
            fetch('/capture')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('拍摄图片失败');
                    }
                    return response.blob();
                })
                .then(blob => {
                    console.log("图片拍摄成功。");
                    const url = URL.createObjectURL(blob);
                    const img = document.getElementById('captured_image');
                    img.src = url;
                    img.style.display = 'block';
                    document.getElementById('video_feed').style.display = 'none';
                })
                .catch(error => {
                    console.error("拍摄图片时出错：", error);
                    alert("拍摄图片失败，请稍后重试。");
                });
        }

        // 启动实时视频流
        function startVideoFeed() {
            console.log("正在启动实时视频流...");
            const videoFeed = document.getElementById('video_feed');
            videoFeed.src = '/video_feed';
            videoFeed.style.display = 'block';
            document.getElementById('captured_image').style.display = 'none';
            updateCameraStatus(true);
        }

        // 停止实时视频流
        function stopVideoFeed() {
            console.log("正在停止实时视频流...");
            const videoFeed = document.getElementById('video_feed');
            videoFeed.src = '';  // 清空视频流
            videoFeed.style.display = 'none';
            closeCamera();  // 停止视频流时关闭摄像头
        }

        // 关闭摄像头
        function closeCamera() {
            console.log("正在关闭摄像头...");
            fetch('/close_camera', { method: 'POST' })
                .then(response => response.json())
                .then(data => {
                    console.log('摄像头已关闭:', data.status);
                    updateCameraStatus(false);
                })
                .catch(error => {
                    console.error("关闭摄像头时出错：", error);
                });
        }

        // 更新摄像头状态指示灯
        function updateCameraStatus(isOn) {
            const statusIndicator = document.getElementById('camera-status');
            if (isOn) {
                statusIndicator.classList.remove('status-off');
                statusIndicator.classList.add('status-on');
            } else {
                statusIndicator.classList.remove('status-on');
                statusIndicator.classList.add('status-off');
            }
        }

        // 页面加载时初始化
        window.onload = function () {
            console.log("页面加载完成，开始初始化...");
            loadCameras();
        };
    </script>
</body>
</html>